import { getOrderCouponPayload } from '@/dataTransfer/coupon';
import { getOrderPointPayload } from '@/dataTransfer/point';
import Taro from '@tarojs/taro';
import { View, Image, Input } from '@tarojs/components';
import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { setMaxRealityDiscountAmountSelected } from '@/dataTransfer/coupon.js';
import pRightIcon from '@/orderSubPack/images/confirmOrder/right-icon.png';
import { SourceType } from '../constant';
import CouponView from './CouponView';
import GiftCardView from './GiftCardView';
import styles from './index.module.scss';
import InvoiceView from './InvoiceView';
import PointView from './PointView';

const OrderPriceDetail = ({
  dispatch,
  discountAmount,
  discountAmountPlat,
  giftCardSelected,

  usableCouponList,
  usableCouponListPlat,
  isAutoCouponDone,

  orderDetail,
  className = '',
  onChange,
}) => {
  const {
    productCarConfirmOrgResponsesList = [],
    expressFee = 0,
    leftOverPrice = 0,
    productTotalPrice = 0,

    discountTotalPrice = 0,
  } = orderDetail;

  const isGetDiscount = orderDetail?.productCarConfirmOrgResponsesList?.length;

  const lastCouponCent = useRef(0);
  // 积分选择结果
  const [selectedPoint, setSelectedPoint] = useState();
  const [hasReqPoint, setHasReqPoint] = useState();

  const orgId = productCarConfirmOrgResponsesList?.[0]?.orgId;
  const merchantId = productCarConfirmOrgResponsesList?.[0]?.merchantId;
  const getInvoiceConfig = () => {
    if (orgId) {
      dispatch({
        type: 'giftCard/getInvoiceConfig',
        payload: { orgId },
      });
    }
  };

  const getOrderCouponList = (sourceType) => {
    dispatch({
      type: 'giftCard/getOrderCouponList',
      payload: getOrderCouponPayload(orderDetail, sourceType, usableCouponList),
    });
  };

  // ========== 价格计算 开始 =============

  // 总价
  let productTotalCent = Math.round(productTotalPrice * 100);
  // 运费
  let expressFeeCent = Math.round(expressFee * 100);

  // 促销优惠
  const promotion = parseFloat(discountTotalPrice);
  const promotionCent = Math.round(promotion * 100);

  // 优惠券折扣
  const couponCent = ((discountAmount ?? 0) + (discountAmountPlat ?? 0)) * 100;
  // 积分折扣
  const pointCent = parseFloat(selectedPoint?.choosePrice ?? 0) * 100;

  // 上述优惠使用之后
  let tempCent = productTotalCent + expressFeeCent - couponCent - pointCent - promotionCent;
  tempCent = tempCent < 0 ? 0 : tempCent;

  // 礼品卡全部
  const giftCardFullCent = giftCardSelected.reduce((pre, cur) => cur.balance * 100 + pre, 0);
  // 礼品卡最大优惠
  const giftCardCent = tempCent < giftCardFullCent ? tempCent : giftCardFullCent;

  const giftCardPrice = giftCardCent / 100;
  const [customerRemark,setCustomerRemark] = useState('')

  // 商品折扣/满减 + 优惠券
  let cheapCent = promotionCent + couponCent;
  if (cheapCent > productTotalCent + expressFeeCent) {
    cheapCent = productTotalCent + expressFeeCent;
  }

  // 全部所有优惠
  let allDiscountPriceCent = promotionCent + couponCent + pointCent + giftCardCent;
  if (allDiscountPriceCent > productTotalCent + expressFeeCent) {
    allDiscountPriceCent = productTotalCent + expressFeeCent;
  }

  // 最终价格
  const submitTotalPrice = (productTotalCent + expressFeeCent - allDiscountPriceCent) / 100;

  const centMap = {
    productTotalCent,
    expressFeeCent,
    promotionCent,
    couponCent,
    pointCent,
    giftCardCent,
    allDiscountPriceCent,
    cheapCent,
  };
  // ========== 价格计算 结束 =============

  // 获取商家券
  useEffect(() => {
    if (!isGetDiscount) {
      return;
    }
    hasReqPoint && setHasReqPoint();
    getOrderCouponList(SourceType.store); //获取商家券
    getOrderCouponList(SourceType.platform); //获取平台券
    getInvoiceConfig();
  }, [orderDetail]);

  // 首次自动选择最大优惠券组合
  useEffect(() => {
    if (isAutoCouponDone) {
      return;
    }

    if (!isGetDiscount) {
      return;
    }

    if (!usableCouponList || !usableCouponListPlat) {
      return;
    }

    setMaxRealityDiscountAmountSelected(usableCouponList, usableCouponListPlat);
    dispatch({
      type: 'giftCard/setOrderCouponListAll',
      payload: { usableCouponList, usableCouponListPlat },
    });
  }, [usableCouponList, usableCouponListPlat]);

  // 商家券=> 平台券 =>  获取积分 抵扣
  useEffect(() => {
    if (!isGetDiscount) {
      return;
    }

    if (!usableCouponList || !usableCouponListPlat || !isAutoCouponDone) {
      return;
    }

    dispatch({
      type: 'order/getOrderPoint',
      payload: getOrderPointPayload(orderDetail, centMap),
    }).then(() => {
      !hasReqPoint && setHasReqPoint(true);
    });
  }, [orderDetail, usableCouponList, usableCouponListPlat, isAutoCouponDone]);

  useEffect(() => {
    if (lastCouponCent.current < couponCent) {
      selectedPoint && setSelectedPoint();
    }

    lastCouponCent.current = couponCent;
  }, [couponCent]);

  // 回传 总价 和 优惠
  useEffect(() => {
    onChange({
      submitTotalPrice,
      selectedPoint,
      discountPrice: cheapCent / 100,
      customerRemark
    });
  }, [submitTotalPrice, selectedPoint, couponCent, pointCent, giftCardCent, discountTotalPrice,customerRemark]);

  const goShoppingMall = () => {
    let url = '/mainSubPack/shoppingMall/index?orgId=' + orgId + '&merchantId=' + merchantId;
    Taro.navigateTo({
      url,
    });
  };

  if (!Object.keys(orderDetail).length) {
    return null;
  }

  if (!hasReqPoint) {
    return null;
  }

  return (
    <View className={`${styles.OrderPriceDetail} ${className}`}>
      <View className="line-plain">
        <View className="label">商品合计</View>
        <View className="value customePageStyle">¥{parseFloat(productTotalPrice).toFixed(2)}</View>
      </View>

      <View className="line-plain">
        <View className="label">运费</View>
        <View className="value">¥{parseFloat(expressFee).toFixed(2)}</View>
      </View>

      {leftOverPrice > 0 && (
        <View className="line-explain">
          <View className="line-explain-ext flex-row-spaceBetween-center">
            <View className="txtleft">还需凑￥{leftOverPrice}可免运费</View>
            <View className="flex-row--center" onClick={() => goShoppingMall()}>
              <View className="txtright">去凑单</View>
              <Image src={pRightIcon} className="icon" />
            </View>
          </View>
        </View>
      )}

      {discountTotalPrice > 0 && (
        <View className="line-plain">
          <View className="label">促销优惠</View>
          <View className="value customePageStyle">
            -¥{parseFloat(discountTotalPrice).toFixed(2)}
          </View>
        </View>
      )}

      <CouponView sourceType={SourceType.store} />
      {/* <CouponView sourceType={SourceType.platform} /> */}

      {/* <PointView
        {...{
          selectedPoint,
          setSelectedPoint,
        }}
      /> */}

      {/* <GiftCardView {...{ orgId, giftCardPrice }} /> */}

      <InvoiceView />
      <View className="line-plain">
        <View className="label">买家留言</View>
        <View className="value"><Input adjustPosition={true} onInput={e=>{
          setCustomerRemark(e.target.value)
        }} className='input' placeholder='留言建议提前协商（250字以内）' /></View>
      </View>

    </View>
  );
};

export default connect(({ loading, productCar, giftCard }) => ({
  loading,

  discountAmountPlat: giftCard.discountAmountPlat,
  discountAmount: giftCard.discountAmount,

  giftCardSelected: productCar.giftCardSelected,

  usableCouponList: giftCard.usableCouponList,

  usableCouponListPlat: giftCard.usableCouponListPlat,

  isAutoCouponDone: giftCard.isAutoCouponDone,
}))(OrderPriceDetail);
